<template>
    <div class="user-setting-container">
        <el-card shadow="hover">
            <div slot="header" class="card-header">
                <h3>博客设置</h3>
            </div>

            <el-loading v-if="loading" text="加载设置数据中..." fullscreen></el-loading>
            <el-form v-else :model="settingForm" label-width="120px" class="setting-form" ref="settingFormRef">
                <!-- <el-form :model="settingForm" label-width="120px" class="setting-form" ref="settingFormRef"> -->
                <el-form-item label="博客名称" required :rules="[{ required: true, message: '博客标题不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.blogName" placeholder="请输入博客标题" style="width: 60%;"></el-input>
                </el-form-item>
                <el-form-item label="作者名" required :rules="[{ required: true, message: '博客标题不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.author" placeholder="请输入博客标题" style="width: 60%;"></el-input>
                </el-form-item>
                <el-form-item label="介绍介绍你" required
                    :rules="[{ required: true, message: '博客描述不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.introduction" type="textarea" rows="3" placeholder="请输入博客描述"
                        style="width: 60%;"></el-input>
                </el-form-item>
                <el-form-item label="博主头像">
                    <el-upload class="avatar-uploader" action="http://47.104.167.34:9110/api/admin/file/upload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="settingForm.avatar" :src="settingForm.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-switch active-text="开启github访问" v-model="acl1" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
                <el-form-item label="github 主页访问地址" required v-model="acl1" v-if="acl1 == true"
                    :rules="[{ required: true, message: 'github访问链接不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.githubHome" placeholder="请输入CSDN url" style="width: 60%;"></el-input>
                </el-form-item>

                <el-switch active-text="开启CSDN访问" v-model="acl2" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
                <el-form-item label="CSDN 主页访问地址" required v-model="acl2" v-if="acl2 == true"
                    :rules="[{ required: true, message: 'CSDN访问链接不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.csdnHome" placeholder="请输入CSDN url" style="width: 60%;"></el-input>
                </el-form-item>
                <el-switch active-text="开启Gitee访问" v-model="acl3" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
                <el-form-item label="Gitee  主页访问地址" required v-model="acl3" v-if="acl3 == true"
                    :rules="[{ required: true, message: 'Gitee访问链接不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.giteeHome" placeholder="请输入CSDN url" style="width: 60%;"></el-input>
                </el-form-item>
                <el-switch active-text="开启Gitee访问" v-model="acl4" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
                <el-form-item label="知乎 主页访问地址" required v-model="acl4" v-if="acl4 == true"
                    :rules="[{ required: true, message: '知乎访问链接不能为空', trigger: 'blur' }]">
                    <el-input v-model="settingForm.zhihuHome" placeholder="请输入知乎 url" style="width: 60%;"></el-input>
                </el-form-item>
            </el-form>

            <div class="form-footer" style="margin-top: 30px; text-align: right;">
                <el-button type="primary" @click="submitSetting" :loading="submitLoading">
                    确认更改
                </el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
export default {
    created() {
        this.getSettingDetail()
    },
    name: 'UserSetting',
    data() {
        return {
            acl1: true,
            acl2: true,
            acl3: true,
            acl4: true,
            imageUrl: '',
            loading: false,
            submitLoading: false,
            defaultAvatar: '',
            avatarFileList: [],
            settingForm: {
            }
        }
    },
    methods: {
        //用接口获取用户
        async getSettingDetail() {
            console.log("开始执行获取用户详情");
            this.loading = true;
            try {
                const res = await this.$axios.post('/api/admin/blog/setting/detail');
                // console.log("请求成功res为：", res);
                if (res.data.success) {
                    const settingData = res.data.data;
                    console.log("输出用户设置数据：", settingData);
                    // 将其字符进行重置
                    this.settingForm = {
                        ...settingData,
                        updateTime: this.formatTime(settingData.updateTime)
                    };
                    //   头像
                    if (settingData.avatar) {
                        this.avatarFileList = [{ url: settingData.avatar }];
                        console.log("头像链接：",this.avatarFileList);
                        
                    }
                } else {
                    this.$message.error(`加载失败：${res.data.message || '未知错误'}`);
                }
            } catch (err) {
                console.log("错误原因是:", err);
                this.$message.error("请求出现错误，请重新发起请求", err)
            } finally {
                this.loading = false;
            }
        },
        handleAvatarUpload(response,) {
            if (response?.success) {
                this.settingForm.authorAvatar = response.data;
                this.avatarFileList = [{ url: response.data }];
            } else {
                this.$message.error('头像上传失败，请重试');
                this.avatarFileList = [];
            }
        },

        formatTime(timestamp) {
            if (!timestamp) return '暂无记录';
            const date = new Date(timestamp);
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
        },

        // 提交修改（唯一操作：确认更改）
        async submitSetting() {
            // 表单校验（仅验证非空）
            const formRef = this.$refs.settingFormRef;
            if (!formRef) return;
            try {
                await formRef.validate();
                this.submitLoading = true;

                const res = await this.$axios.post(
                    '/api/admin/blog/setting/update',
                    this.settingForm //id+修改后参数
                );

                if (res.data.success) {
                    this.$message.success('设置修改成功！');
                    //   最后更新一次
                    this.getSettingDetail();
                } else {
                    this.$message.error(`修改失败：${res.data.message || '未知错误'}`);
                }
            } catch (err) {
                // 表单的校验程序
                if (err.name === 'ValidationError') {
                    this.$message.warning('请完善所有必填项');
                } else {
                    this.$message.error('提交异常，请稍后重试');
                    console.error('SettingUpdate request error:', err);
                }
            } finally {
                this.submitLoading = false;
            }
        },
        async imgupload(file) {
            const res = await this.$axios.post('/api/admin/file/upload', file)
            console.log(res);

        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>

<style scoped>
.user-setting-container {
    padding: 20px;
}

.card-header {
    display: flex;
    align-items: center;
    font-weight: 600;
}

.setting-form {
    margin-top: 20px;
}

.form-footer {
    margin-top: 20px;
}


.el-upload--picture-card {
    width: 120px;
    height: 120px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>